package com.heima.behavior.service.impl;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author csw
 * @since 2025-03-06
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {


    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public ResponseResult saveRead(BehaviorDto dto) {
        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();

        ApBehaviorEntry entry = entryService.getEntryByUserIdOrEquipmentId(user.getUserId(),dto.getEquipmentId());

        // 构建阅读行为对象
        ApReadBehavior readBehavior = new ApReadBehavior();
        readBehavior.setEntryId(entry.getId());
        readBehavior.setArticleId(dto.getArticleId());
        readBehavior.setCount(1);
        readBehavior.setReadDuration(dto.getReadDuration());
        readBehavior.setPercentage(dto.getPercentage());
        readBehavior.setLoadDuration(dto.getLoadDuration());
        readBehavior.setCreatedTime(new Date());
        this.save(readBehavior);
        return ResponseResult.okResult();
    }
}
